const {
  $Toast
} = require('../../../dist/base/index');

const app = getApp();
const request = require('../../../utils/api.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    notDoc: true, //是否有选择文件
    haveDoc: false,
    qiniutoken: "",
    filePath: "",
    fileName: "",
    fileFrom: "",
    fileTypeNo: 0,
    landscape: true,
    fileExtension: ""

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options.fileFrom, "胡茂树")

    if (options.filePath != '' && options.filePath != null) {

      this.setData({
        haveDoc: true,
        notDoc: false,
        fileName: options.fileName,
        filePath: options.filePath,
        fileFrom: options.fileFrom
      })
    }

  },

  //选择的文件
  changeFile: function() {
    var that = this;
    if (this.data.fileFrom == "wx") {
      wx.chooseMessageFile({
        count: 10,
        type: 'file',
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFiles;
          console.log(res, "胡")

          console.log(tempFilePaths[0].name, tempFilePaths[0].path)
          that.setData({
            fileName: tempFilePaths[0].name,
            filePath: tempFilePaths[0].path,
          })
          that.checkFile();
        }
      })
    }
  },

  //文件合法验证，选择文件横纵，
  checkFile: function() {
    var that = this;

    if (that.data.filePath != "" && that.data.filePath != null) {

      var fileExt = that.data.fileName.replace(/.+\./, "");

      var fileExtensionTem = that.data.fileName.substring(that.data.filePath[0].lastIndexOf('.') + 1);
      that.setData({
        fileExtension: fileExtensionTem
      })
      if (fileExtensionTem == "doc" || fileExtensionTem == "docx" || fileExtensionTem == "ppt" || fileExtensionTem == "pptx" || fileExtensionTem == "xls" || fileExtensionTem == "xlsx" || fileExtensionTem == "pdf" || fileExtensionTem == "txt") {

        //获取对应文件类型编码

        if (fileExtensionTem === "xls" || fileExtensionTem === "xlsx") {
          wx.showModal({
            title: '请选择打印方向',
            confirmText: "横向",
            cancelText: "纵向",
            success(res) {
              if (res.confirm) {
                console.log('用户选择横向')
                that.setData({
                  'notDoc': false,
                  'haveDoc': true,
                  landscape: true
                })
                that.upLoadFile();
              } else if (res.cancel) {
                that.setData({
                  'notDoc': false,
                  'haveDoc': true,
                  //filePath: tempFilePaths[0],
                  landscape: false
                })
                that.upLoadFile();
                console.log('用户选择纵向')
              }
            }
          })
        } else {
          that.setData({
            'notDoc': false,
            'haveDoc': true,
            filePath: tempFilePaths[0],
            landscape: true
          })
          that.upLoadFile();
        }
      } else {
        $Toast({
          content: '文件格式不对',
          type: 'warning'
        });
       
      }

      // if (50 * 1024 * 1024){

      // }

    }
  },


  //获取文件类型，并匹配相应的编码
  setFileTypeNo: function() {
    var type = this.data.fileExtension;
    if (type === "doc" || type === "docx") {
      this.setData({
        fileTypeNo: 210
      })
    }

    if (type === "xls" || type === "xlsx") {
      this.setData({
        fileTypeNo: 211
      })
    }
    if (type === "ppt" || type === "pptx") {
      this.setData({
        fileTypeNo: 212
      })
    }
    if (type === "pdf") {
      this.setData({
        fileTypeNo: 213
      })
    }

    if (type === "txt") {
      this.setData({
        fileTypeNo: 214
      })
    }
  },

  //调用文件上传接口，执行文件上传
  upLoadFile: function(e) {
    var that = this;
    const header = {
      'cookie': wx.getStorageSync("setcookie") // 读取cookie
    }
    that.setFileTypeNo();
    console.log(that.data.fileTypeNo, that.data.filePath, that.data.landscape)
    var data = {
      "data": {
        "fileTypeNo": 211,
        "source": 3,
        "file": that.data.filePath,
        "landscape": that.data.landscape
      }
    }
    console.log(data, "HMS")

    wx.uploadFile({
      url: app.globalData.host + '/v3/file/upload_doc',
      filePath: that.data.filePath,
      name: 'file',
      header: header,
      formData: data,
      success: function(res) {
        console.log(res)
        //上传成功再执行页面跳转传值
        wx.navigateTo({
          url: '../' + e.currentTarget.dataset.page + '/' + e.currentTarget.dataset.page + '?fileId=' + e.currentTarget.dataset.fileid + "&fileName=" + e.currentTarget.dataset.filename + "&qiniuUrl=" + e.currentTarget.dataset.qiniuurl + "&fileFrom=" + "library" + "&totalPage=" + e.currentTarget.dataset.total
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })

  },

  // 获取七牛token
  getQiniuToken() {
    const data = {
      url: '/v3/qiniu/token',
      method: "POST",
      param: {
        "fileType": 2
      }
    }
    request(data).then(success => { // 获取qiniu上传文件token
      if (success.data.code === 200) {
        this.setData({
          qiniutoken: success.data.data.token
        })
      }
    }).catch(error => {
      console.log(error)
    })
  },



  docSet: function(e) {
    var that = this;
    if (that.data.fileFrom === "wx") {
      that.checkFile();
      this.upLoadFile(e);
    }


  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})